using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Xml;
using System.Web.Caching;

namespace DiscMaster.Web.Areas.Courses.Controllers
{
    public class JsonCourses
    {
        public string CourseID { get; set; }
        public string Title { get; set; }
        public string Latitude { get; set; }
        public string Longitude { get; set; }
        public string Description { get; set; }
        public string Website { get; set; }
        public string Address { get; set; }
    }
    public class JsonForecasts
    {
        public string DateFrom { get; set; }
        public string DateTo { get; set; }
        public string SymbolNumber { get; set; }
        public string Conditions { get; set; }
        public string Temperature { get; set; }
        public string Precipitation { get; set; }
        public string Wind { get; set; }
        public string WindSpeed { get; set; }
        public string WindDirection { get; set; }
    }

    public class SearchController : Controller
    {
        DiscMaster.Web.Models.DiscMasterRepository repository = new DiscMaster.Web.Models.DiscMasterRepository();

        //
        // AJAX: /Search/SearchCourses

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult SearchCourses()
        {
            var courses = repository.FindAllCourses().OrderBy(c=>c.name).ToList();

            var jsonCourses = from course in courses
                              select new JsonCourses
                              {
                                  CourseID = course.courseid.ToString(),
                                  Latitude = course.CourseDetail.latitude,
                                  Longitude = course.CourseDetail.longitude,
                                  Title = course.name,
                                  Description = course.CourseDetail.description,
                                  Address = course.CourseDetail.address,
                                  Website = course.CourseDetail.website
                              };

            return Json(jsonCourses.ToList());
        }

        //
        // AJAX: /Search/SearchForecasts

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult SearchForecasts(string id)
        {
            var course = repository.GetCourse(id);

            if (!String.IsNullOrEmpty(course.CourseDetail.yr_weather))
            {

                // used to read the forecast xml
                System.Xml.XmlDocument doc = new XmlDocument();
                // our soon-to-be forecast node collection
                System.Xml.XmlNodeList nodelist = null;

                // determine if the forecast is already stored in the cache..
                if (System.Web.HttpContext.Current.Cache[Server.UrlPathEncode(course.CourseDetail.yr_weather)] != null)
                {
                    // .. if so, fetch it
                    doc = (XmlDocument)System.Web.HttpContext.Current.Cache[Server.UrlPathEncode(course.CourseDetail.yr_weather)];
                }
                else
                {
                    // .. and if not, try to consume the source using a reader..
                    try
                    {
                        System.Xml.XmlTextReader reader = new XmlTextReader(Server.UrlPathEncode(course.CourseDetail.yr_weather));
                        doc.Load(reader);
                        // add entry to cache
                        System.Web.HttpContext.Current.Cache.Add(Server.UrlPathEncode(course.CourseDetail.yr_weather), doc, null, DateTime.Now.AddMinutes(60), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
                    }
                    catch (Exception ex)
                    {
                        // just in case something went wrong we allow this to be blank for now..
                    }
                }

                // if all is loaded ok and data is there, simple xpath query to get the forecast data..
                if (doc != null)
                {
                    if (doc.HasChildNodes)
                    {
                        nodelist = doc.SelectNodes("/weatherdata/forecast/tabular/time");
                    }
                }

                if (nodelist != null)
                {
                    if (nodelist.Count > 0)
                    {
                        // iterate each forecast in the current group (day)

                        var jsonForecasts = from node in nodelist.OfType<XmlNode>()
                                            select new JsonForecasts
                                          {
                                              DateFrom = DateTime.Parse(node.Attributes["from"].Value).ToString("yyyy-MM-dd HH:MM"),
                                              DateTo = DateTime.Parse(node.Attributes["to"].Value).ToString("yyyy-MM-dd HH:MM"),
                                              Conditions = node["symbol"].Attributes["name"].Value,
                                              SymbolNumber = node["symbol"].Attributes["number"].Value.PadLeft(2, '0'),
                                              Precipitation = node["precipitation"].Attributes["value"].Value,
                                              Temperature = node["temperature"].Attributes["value"].Value,
                                              Wind = node["windSpeed"].Attributes["name"].Value,
                                              WindDirection = node["windDirection"].Attributes["code"].Value,
                                              WindSpeed = node["windSpeed"].Attributes["mps"].Value
                                          };




                        return Json(jsonForecasts.ToList());
                    }
                }
            }
            return null;
        }
    }
}